package com.mm.cloth.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.CompositePageTransformer;
import androidx.viewpager2.widget.MarginPageTransformer;
import androidx.viewpager2.widget.ViewPager2;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.mm.cloth.R;
import com.mm.cloth.adapter.ToolAdapter;
import com.mm.cloth.fragment.TaskStatusFragment;
import com.mm.cloth.manager.TaskStatusManager;
import com.mm.cloth.model.Banner;
import com.mm.cloth.model.TaskStatus;
import com.mm.cloth.model.Tool;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.widget.LinearLayout;
import com.mm.cloth.utils.LoginCheckUtil;
import com.mm.cloth.utils.WatermarkRemovalAPI;
import java.io.IOException;

public class ToolsFragment extends Fragment {

    private static final String TAG = "ToolsFragment";
    
    // UI组件
    private ViewPager2 bannerViewPager;
    private RecyclerView rvTools;
    private View loadingView;
    private View errorView;
    private TextView btnRetry;
    private ImageView btnTaskStatus;
    
    // 数据
    private List<Banner> bannerList = new ArrayList<>();
    private List<Tool> toolList = new ArrayList<>();
    private BannerAdapter bannerAdapter;
    private ToolAdapter toolAdapter;
    
    // 轮播图自动滚动
    private Handler sliderHandler = new Handler(Looper.getMainLooper());
    private Runnable sliderRunnable = new Runnable() {
        @Override
        public void run() {
            if (bannerViewPager != null) {
                int currentPosition = bannerViewPager.getCurrentItem();
                if (currentPosition == bannerList.size() - 1) {
                    bannerViewPager.setCurrentItem(0);
                } else {
                    bannerViewPager.setCurrentItem(currentPosition + 1);
                }
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tools, container, false);
        initViews(view);
        setupBannerViewPager();
        setupToolsRecyclerView();
        loadData();
        return view;
    }
    
    private void initViews(View view) {
        bannerViewPager = view.findViewById(R.id.bannerViewPager);
        rvTools = view.findViewById(R.id.rvTools);
        loadingView = view.findViewById(R.id.loadingView);
        errorView = view.findViewById(R.id.errorView);
        btnRetry = view.findViewById(R.id.btnRetry);
        btnTaskStatus = view.findViewById(R.id.btnTaskStatus);

        btnRetry.setOnClickListener(v -> loadData());
        btnTaskStatus.setOnClickListener(v -> openTaskStatusPage());
    }

    private void openTaskStatusPage() {
        // 创建任务状态Fragment并显示
        TaskStatusFragment taskStatusFragment = new TaskStatusFragment();

        if (getActivity() != null) {
            getActivity().getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment_container, taskStatusFragment)
                .addToBackStack(null)
                .commit();
        }
    }
    
    private void setupBannerViewPager() {
        bannerAdapter = new BannerAdapter(bannerList);
        bannerViewPager.setAdapter(bannerAdapter);
        
        // 设置页面转换动画
        CompositePageTransformer transformer = new CompositePageTransformer();
        transformer.addTransformer(new MarginPageTransformer(40));
        transformer.addTransformer((page, position) -> {
            float r = 1 - Math.abs(position);
            page.setScaleY(0.85f + r * 0.15f);
        });
        
        bannerViewPager.setPageTransformer(transformer);
        
        // 注册页面变化回调，用于自动滚动
        bannerViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                sliderHandler.removeCallbacks(sliderRunnable);
                sliderHandler.postDelayed(sliderRunnable, 3000);
            }
        });
    }
    
    private void setupToolsRecyclerView() {
        toolAdapter = new ToolAdapter(requireContext(), toolList);
        rvTools.setLayoutManager(new GridLayoutManager(requireContext(), 4));
        rvTools.setAdapter(toolAdapter);
        
        toolAdapter.setOnToolClickListener(tool -> {
            handleNativeToolClick(tool);
        });
    }
    
    private void loadData() {
        showLoading();
        
        // 模拟网络请求
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            // 模拟获取轮播图数据
            bannerList.clear();
            bannerList.add(new Banner(1, "https://example.com/banner1.jpg", "https://example.com/h5/feature1"));
            bannerList.add(new Banner(2, "https://example.com/banner2.jpg", "https://example.com/h5/feature2"));
            bannerList.add(new Banner(3, "https://example.com/banner3.jpg", "https://example.com/h5/feature3"));
            
            // 原生Android工具数据
            toolList.clear();
            toolList.add(new Tool(1, "AI抠图", "", "native_matting"));
            toolList.add(new Tool(2, "前端抠图", "", "native_canvas_matting"));
            toolList.add(new Tool(3, "去水印", "", "native_watermark_removal"));
            toolList.add(new Tool(4, "衣服分割", "", "native_cloth_segmentation"));
            toolList.add(new Tool(5, "换脸", "", "native_face_swap"));
            toolList.add(new Tool(6, "换衣", "", "native_clothes_swap"));
            toolList.add(new Tool(7, "照片清晰", "", "native_photo_enhance"));
            toolList.add(new Tool(8, "AI绘画", "", "native_ai_painting"));
            toolList.add(new Tool(9, "老照片修复", "", "native_photo_restore"));
            toolList.add(new Tool(10, "证件照", "", "native_id_photo"));
            toolList.add(new Tool(11, "更多", "", "native_more"));
            
            // 更新UI
            bannerAdapter.notifyDataSetChanged();
            toolAdapter.notifyDataSetChanged();
            
            showContent();
            
            // 开始轮播
            sliderHandler.postDelayed(sliderRunnable, 3000);
        }, 1500);
    }
    
    private void handleNativeToolClick(Tool tool) {
        String toolType = tool.getUrl(); // 现在url字段存储的是工具类型

        switch (toolType) {
            case "native_matting":
                openMattingTool();
                break;
            case "native_canvas_matting":
                openCanvasMattingTool();
                break;
            case "native_watermark_removal":
                openWatermarkRemovalTool();
                break;
            case "native_cloth_segmentation":
                openClothSegmentationTool();
                break;
            case "native_face_swap":
                openFaceSwapTool();
                break;
            case "native_clothes_swap":
                openClothesSwapTool();
                break;
            case "native_photo_enhance":
                openPhotoEnhanceTool();
                break;
            case "native_ai_painting":
                openAIPaintingTool();
                break;
            case "native_photo_restore":
                openPhotoRestoreTool();
                break;
            case "native_id_photo":
                openIDPhotoTool();
                break;
            case "native_more":
                openMoreTools();
                break;
            default:
                Toast.makeText(requireContext(), "功能即将上线，敬请期待", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private void openMattingTool() {
        Toast.makeText(requireContext(), "打开抠图工具", Toast.LENGTH_SHORT).show();
        // 启动抠图Activity
        Intent intent = new Intent(requireContext(), com.mm.cloth.activity.MattingActivity.class);
        startActivity(intent);
    }

    private void openCanvasMattingTool() {
        Toast.makeText(requireContext(), "打开前端抠图工具", Toast.LENGTH_SHORT).show();
        // 启动Canvas抠图Activity
        Intent intent = new Intent(requireContext(), com.mm.cloth.activity.CanvasMattingActivity.class);
        startActivity(intent);
    }

    private void openWatermarkRemovalTool() {
        Toast.makeText(requireContext(), "启动去水印功能", Toast.LENGTH_SHORT).show();
        
        // 检查用户是否已登录
        if (!LoginCheckUtil.isLoggedIn(requireContext())) {
            LoginCheckUtil.checkLoginAndRedirect(requireContext(), true);
            return;
        }
        
        // 启动WatermarkRemovalActivity
        Intent intent = new Intent(requireContext(), com.mm.cloth.activity.WatermarkRemovalActivity.class);
        startActivity(intent);
    }
    
    private void openClothSegmentationTool() {
        Toast.makeText(requireContext(), "打开衣服分割工具", Toast.LENGTH_SHORT).show();
        // 启动衣服分割Activity
        Intent intent = new Intent(requireContext(), com.mm.cloth.activity.ClothSegmentationActivity.class);
        startActivity(intent);
    }

    private void openFaceSwapTool() {
        // 提交任务到任务管理器
        String taskId = TaskStatusManager.getInstance().submitTask(
            TaskStatus.TaskType.FACE_SWAP,
            "mock_image_path.jpg"
        );

        Toast.makeText(requireContext(), "换脸任务已提交，任务ID: " + taskId, Toast.LENGTH_SHORT).show();

        // 自动跳转到任务状态页面
        openTaskStatusPage();
    }

    private void openClothesSwapTool() {
        String taskId = TaskStatusManager.getInstance().submitTask(
            TaskStatus.TaskType.CLOTHES_SWAP,
            "mock_image_path.jpg"
        );
        Toast.makeText(requireContext(), "换衣任务已提交", Toast.LENGTH_SHORT).show();
        openTaskStatusPage();
    }

    private void openPhotoEnhanceTool() {
        String taskId = TaskStatusManager.getInstance().submitTask(
            TaskStatus.TaskType.PHOTO_ENHANCE,
            "mock_image_path.jpg"
        );
        Toast.makeText(requireContext(), "照片清晰任务已提交", Toast.LENGTH_SHORT).show();
        openTaskStatusPage();
    }

    private void openAIPaintingTool() {
        String taskId = TaskStatusManager.getInstance().submitTask(
            TaskStatus.TaskType.AI_PAINTING,
            "mock_image_path.jpg"
        );
        Toast.makeText(requireContext(), "AI绘画任务已提交", Toast.LENGTH_SHORT).show();
        openTaskStatusPage();
    }

    private void openPhotoRestoreTool() {
        String taskId = TaskStatusManager.getInstance().submitTask(
            TaskStatus.TaskType.PHOTO_RESTORE,
            "mock_image_path.jpg"
        );
        Toast.makeText(requireContext(), "老照片修复任务已提交", Toast.LENGTH_SHORT).show();
        openTaskStatusPage();
    }

    private void openIDPhotoTool() {
        String taskId = TaskStatusManager.getInstance().submitTask(
            TaskStatus.TaskType.ID_PHOTO,
            "mock_image_path.jpg"
        );
        Toast.makeText(requireContext(), "证件照任务已提交", Toast.LENGTH_SHORT).show();
        openTaskStatusPage();
    }

    private void openMoreTools() {
        Toast.makeText(requireContext(), "查看更多工具", Toast.LENGTH_SHORT).show();
        // TODO: 启动更多工具页面
    }
    
    private void showLoading() {
        loadingView.setVisibility(View.VISIBLE);
        errorView.setVisibility(View.GONE);
        bannerViewPager.setVisibility(View.GONE);
        rvTools.setVisibility(View.GONE);
    }
    
    private void showContent() {
        loadingView.setVisibility(View.GONE);
        errorView.setVisibility(View.GONE);
        bannerViewPager.setVisibility(View.VISIBLE);
        rvTools.setVisibility(View.VISIBLE);
    }
    
    private void showError() {
        loadingView.setVisibility(View.GONE);
        errorView.setVisibility(View.VISIBLE);
        bannerViewPager.setVisibility(View.GONE);
        rvTools.setVisibility(View.GONE);
    }
    
    @Override
    public void onPause() {
        super.onPause();
        sliderHandler.removeCallbacks(sliderRunnable);
    }
    
    @Override
    public void onResume() {
        super.onResume();
        sliderHandler.postDelayed(sliderRunnable, 3000);
    }
    
    // Banner适配器
    private class BannerAdapter extends RecyclerView.Adapter<BannerAdapter.BannerViewHolder> {
        
        private List<Banner> banners;
        
        public BannerAdapter(List<Banner> banners) {
            this.banners = banners;
        }
        
        @NonNull
        @Override
        public BannerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_banner, parent, false);
            return new BannerViewHolder(view);
        }
        
        @Override
        public void onBindViewHolder(@NonNull BannerViewHolder holder, int position) {
            Banner banner = banners.get(position);
            
            // 加载图片
            if (getContext() != null) {
                RequestOptions options = new RequestOptions()
                    .placeholder(R.drawable.placeholder_banner)
                    .error(R.drawable.error_banner);
                
                Glide.with(requireContext())
                    .load(banner.getImageUrl())
                    .apply(options)
                    .into(holder.imageView);
            }
            
            // 设置点击事件
            holder.itemView.setOnClickListener(v -> {
                if (banner.getTargetUrl() != null && !banner.getTargetUrl().isEmpty()) {
                    // 使用系统浏览器打开链接
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(banner.getTargetUrl()));
                        requireContext().startActivity(intent);
                    } catch (Exception e) {
                        Toast.makeText(requireContext(), "无法打开链接", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
        
        @Override
        public int getItemCount() {
            return banners.size();
        }
        
        class BannerViewHolder extends RecyclerView.ViewHolder {
            ImageView imageView;
            
            public BannerViewHolder(@NonNull View itemView) {
                super(itemView);
                imageView = itemView.findViewById(R.id.ivBanner);
            }
        }
    }
}